{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wJcYs_ERTnnI"
      },
      "source": [
        "##### Copyright 2021 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "HMUDt0CiUJk9"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "77z2OchJTk0l"
      },
      "source": [
        "# Migrate from TPUEstimator to TPUStrategy\n",
        "\n",
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/migrate/tpu_estimator\">\n",
        "    <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n",
        "    View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/migrate/tpu_estimator.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n",
        "    Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/tpu_estimator.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n",
        "    View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/migrate/tpu_estimator.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "meUTrR4I6m1C"
      },
      "source": [
        "This guide demonstrates how to migrate your workflows running on [TPUs](../../guide/tpu.ipynb) from TensorFlow 1's `TPUEstimator` API to TensorFlow 2's `TPUStrategy` API.\n",
        "\n",
        "- In TensorFlow 1, the `tf.compat.v1.estimator.tpu.TPUEstimator` API lets you train and evaluate a model, as well as perform inference and save your model (for serving) on (Cloud) TPUs.\n",
        "- In TensorFlow 2, to perform synchronous training on TPUs and TPU Pods (a collection of TPU devices connected by dedicated high-speed network interfaces), you need to use a TPU distribution strategy—`tf.distribute.TPUStrategy`. The strategy can work with the Keras APIs—including for model building (`tf.keras.Model`), optimizers (`tf.keras.optimizers.Optimizer`), and training (`Model.fit`)—as well as a custom training loop (with `tf.function` and `tf.GradientTape`).\n",
        "\n",
        "For end-to-end TensorFlow 2 examples, check out the [Use TPUs](../../guide/tpu.ipynb) guide—namely, the *Classification on TPUs* section—and the [Solve GLUE tasks using BERT on TPU](https://www.tensorflow.org/text/tutorials/bert_glue) tutorial. You may also find the [Distributed training](../../guide/distributed_training.ipynb) guide useful, which covers all TensorFlow distribution strategies, including `TPUStrategy`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YdZSoIXEbhg-"
      },
      "source": [
        "## Setup\n",
        "\n",
        "Start with imports and a simple dataset for demonstration purposes:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iE0vSfMXumKI"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "import tensorflow.compat.v1 as tf1"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m7rnGxsXtDkV"
      },
      "outputs": [],
      "source": [
        "features = [[1., 1.5]]\n",
        "labels = [[0.3]]\n",
        "eval_features = [[4., 4.5]]\n",
        "eval_labels = [[0.8]]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4uXff1BEssdE"
      },
      "source": [
        "## TensorFlow 1: Drive a model on TPUs with TPUEstimator"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BVWHEQj5a7rN"
      },
      "source": [
        "This section of the guide demonstrates how to perform training and evaluation with `tf.compat.v1.estimator.tpu.TPUEstimator` in TensorFlow 1.\n",
        "\n",
        "To use a `TPUEstimator`, first define a few functions: an input function for the training data, an evaluation input function for the evaluation data, and a model function that tells the `TPUEstimator` how the training op is defined with the features and labels:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lqe9obf7suIj"
      },
      "outputs": [],
      "source": [
        "def _input_fn(params):\n",
        "  dataset = tf1.data.Dataset.from_tensor_slices((features, labels))\n",
        "  dataset = dataset.repeat()\n",
        "  return dataset.batch(params['batch_size'], drop_remainder=True)\n",
        "\n",
        "def _eval_input_fn(params):\n",
        "  dataset = tf1.data.Dataset.from_tensor_slices((eval_features, eval_labels))\n",
        "  dataset = dataset.repeat()\n",
        "  return dataset.batch(params['batch_size'], drop_remainder=True)\n",
        "\n",
        "def _model_fn(features, labels, mode, params):\n",
        "  logits = tf1.layers.Dense(1)(features)\n",
        "  loss = tf1.losses.mean_squared_error(labels=labels, predictions=logits)\n",
        "  optimizer = tf1.train.AdagradOptimizer(0.05)\n",
        "  train_op = optimizer.minimize(loss, global_step=tf1.train.get_global_step())\n",
        "  return tf1.estimator.tpu.TPUEstimatorSpec(mode, loss=loss, train_op=train_op)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QYnP3Dszc-2R"
      },
      "source": [
        "With those functions defined, create a `tf.distribute.cluster_resolver.TPUClusterResolver` that provides the cluster information, and a `tf.compat.v1.estimator.tpu.RunConfig` object. Along with the model function you have defined, you can now create a `TPUEstimator`. Here, you will simplify the flow by skipping checkpoint savings. Then, you will specify the batch size for both training and evaluation for the `TPUEstimator`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WAqyqawemlcl"
      },
      "outputs": [],
      "source": [
        "cluster_resolver = tf1.distribute.cluster_resolver.TPUClusterResolver(tpu='')\n",
        "print(\"All devices: \", tf1.config.list_logical_devices('TPU'))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HsOpjW5plH9Q"
      },
      "outputs": [],
      "source": [
        "tpu_config = tf1.estimator.tpu.TPUConfig(iterations_per_loop=10)\n",
        "config = tf1.estimator.tpu.RunConfig(\n",
        "    cluster=cluster_resolver,\n",
        "    save_checkpoints_steps=None,\n",
        "    tpu_config=tpu_config)\n",
        "estimator = tf1.estimator.tpu.TPUEstimator(\n",
        "    model_fn=_model_fn,\n",
        "    config=config,\n",
        "    train_batch_size=8,\n",
        "    eval_batch_size=8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Uxw7tWrcepaZ"
      },
      "source": [
        "Call `TPUEstimator.train` to begin training the model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WZPKFOMAcyrP"
      },
      "outputs": [],
      "source": [
        "estimator.train(_input_fn, steps=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ev1vjIz9euIw"
      },
      "source": [
        "Then, call `TPUEstimator.evaluate` to evaluate the model using the evaluation data:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bqiKRiwWc0cz"
      },
      "outputs": [],
      "source": [
        "estimator.evaluate(_eval_input_fn, steps=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KEmzBjfnsxwT"
      },
      "source": [
        "## TensorFlow 2: Drive a model on TPUs with Keras Model.fit and TPUStrategy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UesuXNbShrbi"
      },
      "source": [
        "In TensorFlow 2, to train on the TPU workers, use `tf.distribute.TPUStrategy` together with the Keras APIs for model definition and training/evaluation. (Refer to the [Use TPUs](../../guide/tpu.ipynb) guide for more examples of training with Keras `Model.fit` and a custom training loop (with `tf.function` and `tf.GradientTape`).)\n",
        "\n",
        "Since you need to perform some initialization work to connect to the remote cluster and initialize the TPU workers, start by creating a `TPUClusterResolver` to provide the cluster information and connect to the cluster. (Learn more in the *TPU initialization* section of the [Use TPUs](../../guide/tpu.ipynb) guide.)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_TgdPNgXoS63"
      },
      "outputs": [],
      "source": [
        "cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')\n",
        "tf.config.experimental_connect_to_cluster(cluster_resolver)\n",
        "tf.tpu.experimental.initialize_tpu_system(cluster_resolver)\n",
        "print(\"All devices: \", tf.config.list_logical_devices('TPU'))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R4EHXhN3CVmo"
      },
      "source": [
        "Next, once your data is prepared, you will create a `TPUStrategy`, define a model, metrics, and an optimizer under the scope of this strategy.\n",
        "\n",
        "To achieve comparable training speed with `TPUStrategy`, you should make sure to pick a number for `steps_per_execution` in `Model.compile` because it specifies the number of batches to run during each `tf.function` call, and is critical for performance. This argument is similar to `iterations_per_loop` used in a `TPUEstimator`. If you are using custom training loops, you should make sure multiple steps are run within the `tf.function`-ed training function. Go to the *Improving performance with multiple steps inside tf.function* section of the [Use TPUs](../../guide/tpu.ipynb) guide for more information.\n",
        "\n",
        "`tf.distribute.TPUStrategy` can support bounded dynamic shapes, which is the case that the upper bound of the dynamic shape computation can be inferred. But dynamic shapes may introduce some performance overhead compared to static shapes. So, it is generally recommended to make your input shapes static if possible, especially in training. One common op that returns a dynamic shape is `tf.data.Dataset.batch(batch_size)`, since the number of samples remaining in a stream might be less than the batch size. Therefore, when training on the TPU, you should use `tf.data.Dataset.batch(..., drop_remainder=True)` for best training performance."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "atVciNgPs0fw"
      },
      "outputs": [],
      "source": [
        "dataset = tf.data.Dataset.from_tensor_slices(\n",
        "    (features, labels)).shuffle(10).repeat().batch(\n",
        "        8, drop_remainder=True).prefetch(2)\n",
        "eval_dataset = tf.data.Dataset.from_tensor_slices(\n",
        "    (eval_features, eval_labels)).batch(1, drop_remainder=True)\n",
        "\n",
        "strategy = tf.distribute.TPUStrategy(cluster_resolver)\n",
        "with strategy.scope():\n",
        "  model = tf.keras.models.Sequential([tf.keras.layers.Dense(1)])\n",
        "  optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05)\n",
        "  model.compile(optimizer, \"mse\", steps_per_execution=10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FkM2VZyni98F"
      },
      "source": [
        "With that, you are ready to train the model with the training dataset:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Kip65sYBlKiu"
      },
      "outputs": [],
      "source": [
        "model.fit(dataset, epochs=5, steps_per_epoch=10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r0AEK8sNjLOj"
      },
      "source": [
        "Finally, evaluate the model using the evaluation dataset:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6tMRkyfKhqSL"
      },
      "outputs": [],
      "source": [
        "model.evaluate(eval_dataset, return_dict=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "67ec4d3f35d6"
      },
      "source": [
        "## Next steps"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gHx_RUL8xcJ3"
      },
      "source": [
        "To learn more about `TPUStrategy` in TensorFlow 2, consider the following resources:\n",
        "\n",
        "- Guide: [Use TPUs](../../guide/tpu.ipynb) (covering training with Keras `Model.fit`/a custom training loop with `tf.distribute.TPUStrategy`, as well as tips on improving the performance with `tf.function`)\n",
        "- Guide: [Distributed training with TensorFlow](../../guide/distributed_training.ipynb)\n",
        "\n",
        "To learn more about customizing your training, refer to:\n",
        "- Guide: [Customize what happens in Model.fit](../..guide/keras/customizing_what_happens_in_fit.ipynb)\n",
        "- Guide: [Writing a training loop from scratch](https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch)\n",
        "\n",
        "TPUs—Google's specialized ASICs for machine learning—are available through [Google Colab](https://colab.research.google.com/), the [TPU Research Cloud](https://sites.research.google/trc/), and [Cloud TPU](https://cloud.google.com/tpu)."
      ]
    }
  ],
  "metadata": {
    "accelerator": "TPU",
    "colab": {
      "collapsed_sections": [],
      "name": "tpu_estimator.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
